package com.lagou.interceptor;

import com.lagou.annotation.Security;
import com.lagou.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * desc:
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 17/9/2020
 */
public class ValidInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username = request.getParameter("username");

        //校验method是否有Security，有的话进行权限校验
        Method method = ((Handler) handler).getMethod();
        boolean methodAnnotationPresent = method.isAnnotationPresent(Security.class);
        if (methodAnnotationPresent) {
            doValid(username, method.getAnnotation(Security.class));
            //如果method有Security注解的话，无需校验controller，直接返回即可
            return true;
        }

        //校验controller是否有Security，有的话进行权限校验
        Object controller = ((Handler) handler).getController();
        Class<?> controllerClass = controller.getClass();
        boolean annotationPresent = controllerClass.isAnnotationPresent(Security.class);
        if (annotationPresent) {
            doValid(username, controllerClass.getAnnotation(Security.class));
        }

        return true;
    }

    private void doValid(String username, Security annotation) {
        String[] value = annotation.value();
        boolean contains = Arrays.asList(value).contains(username);
        if (!contains) {
            throw new RuntimeException("No Access.");
        }
    }
}
